//	--------------------------------------------------------------------
//	Copyright(C) 2006,2007 Zhao Yukun. All rights reserved.
//	This file is a part of the Xeres system.
//	Xeres 2007
//	Contact : xeres.engine@gmail.com
//	$(reservedInfo)
//	$(reservedDeclaration)
//	--------------------------------------------------------------------
///	@file	<CShadingPass9.cpp>
///	@path	~/src/graphics/dx9/
///	@date	2007/11/15
///	@desc	Forward shading pass.

#include "config/config.h"

#include "lib/system/thread_debug.h"

#include "graphics/dx9/import_dx9.h"
#include "graphics/dx9/CShadingPass9.h"
#include "graphics/dx9/CRenderer9.h"
#include "graphics/common/CPerspectiveView.h"

namespace xeres {

	IMPL_IOBJECT_CLASS_DYNAMIC( CShadingPass9 );

	// ctor
	CShadingPass9::CShadingPass9( void )
		: m_backgroundColor( 0 )
	{
		m_view = new CPerspectiveView;
	}

	// dtor
	CShadingPass9::~CShadingPass9( void )
	{
	}

	// initialize
	void CShadingPass9::Initialize( RefWeak<IDevice> device )
	{
		TRACK_FUNCTION_SCOPE();
		RUNNING_ON_THREAD( _S("device") );
		// we should make buffer here
	}

	// finalize
	void CShadingPass9::Finalize( void )
	{
		TRACK_FUNCTION_SCOPE();
		RUNNING_ON_THREAD( _S("device") );
	}

	// begin pass
	void CShadingPass9::Begin( RenderContext& rc )
	{
		TRACK_FUNCTION_SCOPE();
		RUNNING_ON_THREAD( _S("render") );

		rc.GetRenderer9()->RestoreDefaultState();
		rc.GetDX9()->SetRenderState( D3DRS_CULLMODE , D3DCULL_NONE );
		rc.GetDX9()->SetRenderState( D3DRS_LIGHTING, FALSE );

		rc.GetDX9()->Clear( 0 , NULL , D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER ,
				m_backgroundColor.get_packed_argb() , 1.f , 0 );

		if( m_view.IsValid() )
		{
			m_view->Reset( rc );

			Matrix<float> transform = m_view->GetTransform();
			Matrix<float> projection = m_view->GetProjection();
			// Setup camera.
			rc.GetDX9()->SetTransform( D3DTS_WORLD , (const D3DMATRIX*)&Matrix<float>::_identity() );
			rc.GetDX9()->SetTransform( D3DTS_VIEW , (D3DMATRIX*)&transform );
			rc.GetDX9()->SetTransform( D3DTS_PROJECTION , (D3DMATRIX*)&projection );
		}
		else
		{
			rc.GetDX9()->SetTransform( D3DTS_WORLD , (const D3DMATRIX*)&Matrix<float>::_identity() );
			rc.GetDX9()->SetTransform( D3DTS_VIEW , (const D3DMATRIX*)&Matrix<float>::_identity() );
			rc.GetDX9()->SetTransform( D3DTS_PROJECTION , (const D3DMATRIX*)&Matrix<float>::_identity() );
		}
	}

	// end pass
	void CShadingPass9::End( RenderContext& rc )
	{
		TRACK_FUNCTION_SCOPE();
		RUNNING_ON_THREAD( _S("render") );
	}

	// SetPassView
	void CShadingPass9::SetPassView( RefWeak<IView> view )
	{
		m_view = view;
	}
	// GetPassView
	RefWeak<IView> CShadingPass9::GetPassView( void )
	{
		return m_view;
	}

} // namespace xeres
